package com.test.juc.resource;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ShareResource {

    private int lockTag = 1;
    private final Lock locker = new ReentrantLock();
    private final Condition condition1 = locker.newCondition();
    private final Condition condition2 = locker.newCondition();
    private final Condition condition3 = locker.newCondition();

    public void print5(int loop) throws InterruptedException {
        locker.lock();
        try {
            while (lockTag != 1) {
                condition1.await();
            }

            for (int i = 0; i < 5; i++) {
                System.out.printf("%s :: %d :: %d\n", Thread.currentThread().getName(), i, loop);
            }

            lockTag = 2;
            condition2.signal();
        } finally {
            locker.unlock();
        }
    }

    public void print10(int loop) throws InterruptedException {
        locker.lock();
        try {
            while (lockTag != 2) {
                condition2.await();
            }

            for (int i = 0; i < 10; i++) {
                System.out.printf("%s :: %d :: %d\n", Thread.currentThread().getName(), i, loop);
            }

            lockTag = 3;
            condition3.signal();
        } finally {
            locker.unlock();
        }
    }

    public void print15(int loop) throws InterruptedException {
        locker.lock();
        try {
            while (lockTag != 3) {
                condition3.await();
            }

            for (int i = 0; i < 15; i++) {
                System.out.printf("%s :: %d :: %d\n", Thread.currentThread().getName(), i, loop);
            }

            lockTag = 1;
            condition1.signal();
        } finally {
            locker.unlock();
        }
    }
}
